package com.apestech.api.condition.Step;

import com.apestech.api.condition.ConditionExec;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.xml.condition.modul.ConditionStrategy;

public class StepQuery extends StepPubField {
    private ArrayCallback arrayCallback;
    private boolean bwhile=false;

    public StepQuery(ConditionStrategy.Step step, SqlSession session) throws Exception {
        super(step, session);
        if(step.isAlldata()){
            if(step.getId()==null && step.getMutikey()==null){
                throw new Exception("sql类型的结点，如有配置返回多条记录，属性[mutikey]不能为空，请补全配置！");
            }
        }
        super.setInput(null);
        super.setResultMap(null);
    }

    public void setBwhile(boolean bwhile) {
        this.bwhile = bwhile;
    }

    public void setArrayCallback(ArrayCallback arrayCallback) {
        this.arrayCallback = arrayCallback;
    }

    @Override
    public void setInput(JSONObject input) throws Exception {
        super.setInput(input);
        if(super.getStep().getFrom()!=null){
            super.getInput().put("nb_from",super.getStep().getFrom());
        }
        if(super.getInput().get("autoCompletion")==null){
            super.getInput().put("autoCompletion","0");
        }
    }

    @Override
    public void exec() throws Exception {
        SqlSession esession=getStepDb(super.getStep().getDb(), super.getSession());
        ConditionStrategy.Step step=super.getStep();
        QueryCallBackHandler queryCallBackHandler=new QueryCallBackHandler(){
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                JSONObject m=new JSONObject();
                JSONArray qlist=new JSONArray();
                while(rs.next()){
                    JSONObject m1=new JSONObject();
                    m1.putAll(rs.toRowJson());
                    if(arrayCallback!=null){
                        JSONObject m3=new JSONObject();
                        m3.putAll(m1);
                        JSONObject m2=arrayCallback.getRow(m3);
                        m1.putAll(m2);
                    }
                    if(step.isAlldata()){
                        m1.remove("condition");
                        m1.remove("autoCompletion");
                        m1.remove("SYS_RQ");
                        qlist.add(m1);
                    } else {
                        m=m1;
                    }
                    if(!bwhile){
                        break;
                    }
                }
                if(step.isAlldata()){
                    if(qlist!=null && qlist.size()>0){
                        if(step.getMutikey()!=null){
                            m.put(step.getMutikey(), qlist);
                        } else {
                            m.put(step.getId(), qlist);
                        }
                    }
                }
                step.setResultMap(m);
            }
        };

        try {
            if ("sql".equals(step.getType())) {
                String sql=step.getSql();
                if(step.getCid()!=null && step.getDimfield()!=null){
                    ConditionExec exec=new ConditionExec(esession, step.getCid());
                    JSONObject inp=new JSONObject();
                    inp.put("SYS_DIM_FIELD", step.getDimfield());
                    String sql1=exec.qryConditionMidTabName(inp);
                    if(sql1==null){
                        return;
                    }
                    super.getInput().put("nb_from", sql1+"_EXEC");
                    sql1=" SELECT * FROM "+sql1+"_EXEC A WHERE 1=1 ";
                    if(sql.indexOf("#SQL#")>=0){
                        sql=sql.replace("#SQL#", " "+sql1+" ");
                    } else {
                        sql=sql1+" "+sql+" ";
                    }
                }
                esession.getForResultSet().sql(sql, super.getInput(), queryCallBackHandler);
            } else {
                esession.getForResultSet().queryId(step.getId(), super.getInput(), queryCallBackHandler);
            }
            if(step.isIsbreak()){
                JSONObject r=step.getResultMap();
                if(r==null || r.size()==0){
                    r=new JSONObject();
                    r.put("sys_break","1");
                    step.setResultMap(r);
                }
            }
        } catch (Exception e){
            throw new Exception(e);
        } finally {
            closeSession(super.getSession(), esession);
        }
        finiExec(step.getResultMap(), step);
        step.setResultMap(step.getResultMap());
    }

}
